import React from 'react';
import Tab from "react-bootstrap/lib/Tab";
import Button from "react-bootstrap/lib/Button";
import HttpRequest from '../HttpRequest.js';
import OrderList from './orderList.jsx';
import ListItem from 'material-ui/lib/lists/list-item';
import WorkspaceManage from "./../workspace/workspaceManage.jsx";
import Image from '../../../../node_modules/react-bootstrap/lib/Image';
import msgFrontAgent from  '../msgFrontAgent.js'

var order_list = [];
var local_repo = [];
var dependencies = [];
var ProjectInfoTab = React.createClass({

    getInitialState: function () {
        return ({
            orders: null,
            pro_dep: null,
            local_repo: null,
            dep_item: [],
            dependency_info: null,
            current_project: this.props.current_project
        });
    },
    componentWillReceiveProps: function (newProps) {
        this.setState({
            current_project: newProps.current_project
        }, this.componentWillMount);

    },
    componentDidMount: function () {
        //监听所有可能的界面事件 添加订阅
        var that = this;
        msgFrontAgent.onConnected(function () {
                msgFrontAgent.order('dependency_download', function () {
                    that.componentWillMount();
                });
                msgFrontAgent.order('dependency_update', function () {
                    that.componentWillMount();
                });
            }
        );

    },

    _getDependencies: function (callback) {
        if (this.state.current_project._id) {
            HttpRequest.getProject(this.state.current_project._id).success(function (msg) {
                if (msg.code == 0) {
                    dependencies = msg.data.dependencies;
                    callback();
                } else {
                    //console.log("获取依赖信息失败");
                    return false;
                }
            }).error(()=> {
                //console.log("获取依赖信息失败");
                return false;
            });
        }

    },

    _getOrders: function (callback) {
        HttpRequest.getCurrentUser().success(function (res) {
            if (res.code == 0) {
                HttpRequest.getOrders(res.data.shortid).success(function (msg) {
                    if (msg.code == 0) {
                        order_list = msg.data;
                        callback();
                    } else {
                        return false;
                    }
                });
            } else {
                return false;
            }
        }).error(()=> {
            //console.log("获取依赖信息失败");
            return false;
        });
    },

    _getLocalRepo: function (callback) {
        HttpRequest.getLocalRepo().success(function (msg) {
            if (msg.code == 0) {
                local_repo = msg.data;
                callback();
            } else {
                return false;
            }
        }).error(()=> {
            return false;
        });
    },
    _renderDepItems: function (deps) {
        var that = this;
        var dep_item = [];
        var btn = null;
        if (deps) {
            deps.map(function (item, index) {
                var info = JSON.stringify(item);
                switch (item.status) {
                    case 0:
                        btn =
                            <div>
                                <img src="/res/image/delete.png"
                                     id={that.state.current_project.name+"_delete_"+index}
                                     title="删除"
                                     onClick={function(){that.dependencyOperation("delete",item,index)}}
                                     style={{cursor:"pointer",float:"right",width:"21px",height:"21px"}}/>
                                <img src="/res/image/update.png"
                                     id={that.state.current_project.name+"_order_"+index}
                                     title="订阅"
                                     style={{marginRight:"10px",float:"right",width:"21px",height:"21px"}}
                                     onClick={function(){that.dependencyOperation("order",item,index)}}/>
                            </div>;

                        break;
                    case 1:
                        btn =
                            <div>
                                <img src="/res/image/delete.png"
                                     id={that.state.current_project.name+"_delete_"+index}
                                     title="删除"
                                     onClick={function(){that.dependencyOperation("delete",item,index)}}
                                     style={{cursor:"pointer",float:"right",width:"21px",height:"21px"}}/>
                                <img src="/res/image/download.png"
                                     id={that.state.current_project.name+"_download_"+index}
                                     title="下载"
                                     style={{cursor:"pointer",marginRight:"10px",float:"right",width:"21px"}}
                                     onClick={function(){that.dependencyOperation("download",item,index)}}/>
                            </div>;
                        break;
                    case 2:
                        btn =
                            <div>
                                <img src="/res/image/delete.png"
                                     id={that.state.current_project.name+"_delete_"+index}
                                     title="删除"
                                     onClick={function(){that.dependencyOperation("delete",item,index)}}
                                     style={{cursor:"pointer",float:"right",width:"21px",height:"21px"}}/>
                                <img src="/res/image/sync.png"
                                     id={that.state.current_project.name+"_update_"+index}
                                     title="更新"
                                     style={{cursor:"pointer",marginRight:"10px",float:"right",width:"21px"}}
                                     onClick={function(){that.dependencyOperation("update",item,index)}}/>
                            </div>;
                        break;
                    case 3:
                        btn =
                            <div>
                                <img src="/res/image/delete.png"
                                     id={that.state.current_project.name+"_delete_"+index}
                                     title="删除"
                                     style={{cursor:"pointer",float:"right",width:"21px",height:"21px"}}
                                     onClick={function(){that.dependencyOperation("delete",item,index)}}/>
                            </div>;
                        break;
                    case 4:
                        btn =
                            <div>
                                <img src="/res/image/delete.png"
                                     id={that.state.current_project.name+"_delete_"+index}
                                     title="删除"
                                     onClick={function(){that.dependencyOperation("delete",item,index)}}
                                     style={{cursor:"pointer",float:"right",width:"21px",height:"21px"}}/>
                                <i className='fa fa-spinner fa-pulse'
                                   id={that.state.current_project.name+"_downloading_"+index}
                                   title='下载中'
                                   style={{color:'#ff9600',marginRight: '10px',float: 'right',fontSize:'21px',cursor:'pointer'}}>
                                </i>
                            </div>;
                        break;
                }
                dep_item.push(
                    <tr id={"dep_"+ index}
                        key={index}
                        onClick={that.selectDependency.bind(that,index)}
                        style={{borderBottom: "#C4C4C4 1px solid",height:"65px",fontSize:"15px"}}>
                        <td style={{cursor:"pointer",paddingTop:"24px"}}>{item.goods_title}</td>
                        <td style={{paddingTop:"24px"}} id="dep_operation_btn">
                            {btn}
                        </td>
                        <td style={{display:"none"}}>
                            {info}
                        </td>
                    </tr>)
            });
        }
        that.setState({
            pro_dep: deps,
            dep_item: dep_item,
            orders: order_list
        }, function () {
            that.selectDependency(0)
        });
    },
    componentWillMount: function () {
        var that = this;

        document.getElementById("world").addEventListener('click', ()=>{document.getElementById("world").focus()});
        //that._getDependencies(function () {
        if (this.state.current_project._id) {
            HttpRequest.getProject(this.state.current_project._id).success(function (msg) {
                if (msg.code == 0) {
                    that.setState({
                        projectTitle: <div tabIndex="0" onBlur={this.onblur}>
                            {
                                <i className="fa fa-edit" title="编辑"
                                style={{float:"right",marginRight:"10px",fontSize:"19px",cursor:"pointer"}}
                                onClick={that.editProjectTitle}/>
                            }
                            <div>
                                <h4 style={{fontSize: "16px", marginBottom: "20px"}}>标&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    题：{msg.data.title}</h4>
                            </div>
                        </div>,
                        current_project:msg.data
                    });
                    dependencies = msg.data.dependencies;
                    that._getOrders(function () {
                        that._getLocalRepo(function () {
                            if (dependencies.length > 0) {
                                that._getDependenciesStatus(dependencies, order_list, local_repo, function (deps) {
                                    that._renderDepItems(deps);
                                });
                            } else {
                                that.setState({
                                    pro_dep: [],
                                    dep_item: []
                                });
                            }
                        });
                    });
                } else {
                    //console.log("获取依赖信息失败");
                    return false;
                }
            }).error(()=> {
                //console.log("获取依赖信息失败");
                return false;
            });
        }
        //});
    },

    componentWillUnmount: function () {
        msgFrontAgent.onConnected(function () {
                msgFrontAgent.disorder('dependency_download');
                msgFrontAgent.disorder('dependency_update');
            }
        );
    },

    selectDependency: function (index) {
        var selected = this.state.pro_dep[index];
        for (var count = 0; count < this.state.pro_dep.length; count++) {
            var btn_delete = document.getElementById(this.state.current_project.name + "_delete_" + count);
            var btn_update = document.getElementById(this.state.current_project.name + "_update_" + count);
            var btn_download = document.getElementById(this.state.current_project.name + "_download_" + count);
            var btn_order = document.getElementById(this.state.current_project.name + "_order_" + count);
            var downloading = document.getElementById(this.state.current_project.name + "_downloading_" + count);
            if (btn_delete) {
                btn_delete.src = count == index ? "/res/image/delete_h.png" : "/res/image/delete.png";
            }
            if (btn_update) {
                btn_update.src = count == index ? "/res/image/sync_h.png" : "/res/image/sync.png";
            }
            if (btn_download) {
                btn_download.src = count == index ? "/res/image/download_h.png" : "/res/image/download.png";
            }
            if (btn_order) {
                btn_order.src = count == index ? "/res/image/update_h.png" : "/res/image/update.png";
            }
            if (downloading) {
                downloading.style.color = count == index ? "#ff9600" : "#E7E7E7";
            }
        }

        var dependency_info = <div style={{ fontSize:"16px",color:"#4d5359"}}>
            <h4 style={{padding:" 20px 15px",fontSize: "18px"}}>依赖详细信息</h4>
            <h4 style={{paddingLeft:"20px",fontSize: "15px", marginBottom: "20px"}}>名称：{selected.goods_title}</h4>
            <h4 style={{paddingLeft:"20px",fontSize: "15px", marginBottom: "20px"}}>版本：{selected.goods_version}</h4>
            <h4 style={{paddingLeft:"20px",fontSize: "15px", marginBottom: "20px"}}>提供商：{selected.supplier}</h4>
            <h4 style={{paddingLeft:"20px",fontSize: "15px", marginBottom: "20px"}}>简介：{selected.introduction}</h4>
            <h4 style={{paddingLeft:"20px",fontSize: "15px", marginBottom: "20px"}}>类型：{selected.type}</h4>
            <h4 style={{paddingLeft:"20px",fontSize: "15px", marginBottom: "20px"}}>产品信息：{selected.introduction}</h4>
        </div>
        this.setState({
            dependency_info: dependency_info
        });
    },
    dependencyOperation: function (operation, item, index) {
        var ob = this;
        switch (operation) {
            case "order":
                window.open("http://123.56.199.100:8180");
                break;
            case "delete":
                confirm("确定要删除依赖吗？", function () {
                    HttpRequest.removeDependency(this.props.current_project._id, item).success(function (res) {
                        ob.setState({
                            dependency_info: null
                        }, ob.componentWillMount);
                    }).error(function (msg) {
                        toastr.error(null, "删除失败");
                    });
                }.bind(this));
                break;
            case "download":
                var data = {
                    fileName: item.name,
                    version: item.goods_version,
                    other_info: item.custom_data,
                    type: item.type
                };
                var downloading = document.createElement("i");
                downloading.setAttribute("class", "fa fa-spinner fa-pulse");
                downloading.setAttribute("id", ob.state.current_project.name + "_downloading_" + index);
                downloading.setAttribute("style", "color:#ff9600;margin-right: 10px;float: right;font-size:21px;cursor:pointer");
                downloading.setAttribute("title", "下载中");
                var download_btn = document.getElementById(ob.state.current_project.name + "_download_" + index);
                var parentNode = download_btn.parentNode;
                parentNode.showLoading = function () {
                    parentNode.removeChild(download_btn);
                    parentNode.appendChild(downloading);
                };
                parentNode.showLoadBtn = function () {
                    parentNode.removeChild(downloading);
                    parentNode.appendChild(download_btn);
                };
                confirm("确定要下载依赖文件吗？", function () {
                    parentNode.showLoading();
                    HttpRequest.downloadToRepo(data).success(function (msg) {
                        if (msg.code == 200) {
                            let task_id = msg.data.task_id;
                            toastr.success(null, '下载任务开始执行...');
                            msgFrontAgent.order(task_id, function (data) {
                                if (data.err) {
                                    parentNode.showLoadBtn();
                                    toastr.error(null, data.err, {timeOut: 0});
                                } else {
                                    // TODO:: 有个界面bug 回头有时间再修改
                                    //parentNode.removeChild(downloading);
                                    ob.componentWillMount();
                                    toastr.success(null, data.body.fileName + "下载成功", {timeOut: 0});
                                }
                            });
                        } else {
                            parentNode.showLoadBtn();
                            toastr.error(null, "下载任务失败", {timeOut: 0});
                        }
                    }).error(function (msg) {
                        parentNode.showLoadBtn();
                        toastr.error(null, "下载任务失败", {timeOut: 0});
                    });
                });
                break;
            case "update":
                var thisOb = this;
                confirm("确定更新？", function () {
                    var index = _.findIndex(thisOb.state.orders, function (goods) {
                        return goods.name == item.name;
                    });
                    var data = {
                        fileName: item.name,
                        version: thisOb.state.orders[index].goods_version,
                        other_info: item.custom_data,
                        type: item.type
                    };
                    HttpRequest.updateRepo(data).success(function (res) {
                        if (res.code == 200) {
                            let task_id = res.data.task_id;
                            toastr.success(null, '依赖更新开始...');
                            msgFrontAgent.order(task_id, function (data) {
                                if (data.err) {
                                    toastr.error(null, data.err, {timeOut: 0});
                                } else {
                                    item.status = 3;
                                    item.goods_version = thisOb.state.orders[index].goods_version;
                                    HttpRequest.updateDependency(ob.props.current_project._id, item).success(function (res) {
                                        toastr.success(null, item.name + '更新完成！', {timeOut: 0});
                                        ob.componentWillMount();
                                    }).error(function (msg) {
                                        toastr.error(null, "更新依赖信息失败！");
                                    });
                                }
                            });
                        } else {
                            toastr.error(null, "更新依赖信息失败！", {timeOut: 0});
                        }

                    }.bind(this)).error(function (msg) {
                        toastr.error(null, "更新依赖信息失败！", {timeOut: 0});
                    });
                }.bind(this));
                break;
        }

    },
//    项目依赖中是否在订阅列表中
//    是：项目依赖中的版本是否和订阅版本一致
//       是：项目依赖（name + version）是否存在于本地仓库
//           是：检查该版本是否为downloading
//               是：正在下载  (code : 4)
//               否：正常状态  (code : 3)
//           否：需下载（name + version ） （code ： 1）
//       否：需更新  (code ：2)
//    否：未订阅  （code : 0）

//

    _getDependenciesStatus: function (dependencies_infos, order_list, local_repo, callback) {
        var that = this;
        dependencies_infos.map(function (dependency, index) {
            var indexInLocal = _.findIndex(local_repo, {
                fileName: dependency.name,
                version: dependency.goods_version
            });
            if (_.findIndex(order_list, {name: dependency.name}) < 0) {
                dependencies_infos[index].status = 0;
            } else if (_.findIndex(order_list, {name: dependency.name, goods_version: dependency.goods_version}) < 0) {
                dependencies_infos[index].status = 2;
            } else if (indexInLocal < 0) {
                dependencies_infos[index].status = 1;
            } else if (indexInLocal >= 0 && local_repo[indexInLocal].other_info == 'downloading') {
                dependencies_infos[index].status = 4;
            } else {
                dependencies_infos[index].status = 3;
            }
            //HttpRequest.updateDependency(that.props.current_project._id, dependencies_infos[index]).success(function (res) {
            //    //that.componentWillMount();
            //}).error(function (msg) {
            //    toastr.error(null, "更新依赖信息失败！");
            //});
        });
        HttpRequest.updateDependencies(that.props.current_project._id, dependencies_infos).success(function (res) {
            //that.componentWillMount();
            callback(dependencies_infos);
        }).error(function (msg) {
            toastr.error(null, "更新依赖信息失败！");
        });

    },
    handleOPen: function () {
        this.refs['order_list_nav'].handleToggle()
    },
    refresh: function (dependencies) {
        this.setState({
            pro_dep: dependencies
        }, this.componentWillMount);
    },
    updateTarget: function () {
        //var that = this;
        var project_id = this.props.current_project._id;
        var options = {
            project_id: project_id
        };
        //HttpRequest.updateTargetByProjectId(options).success(function (res) {
        //    if (res.code == 200) {
        //        window.loading();
        //        let task_id = res.data.task_id;
        //        msgFrontAgent.order(task_id, function (data) {
        //            if (data.err) {
        //                toastr.error(null, data.err, {timeOut: 0});
        //            } else {
        //                toastr.success(null, data.body.msg);
        //            }
        //            window.removeLoading();
        //        }.bind(this));
        //    }
        //}.bind(this)).error(function (err) {
        //    toastr.error(null, "更新失败!");
        //});
    },
    confirmEdit: function () {
        var title = document.getElementById("project-edit-title").value;
        HttpRequest.updateProject(this.state.current_project._id, {title: title}).success(
            function (res) {
                if (res.code == 200) {
                    toastr.success(null, "项目标题修改成功");
                    this.refresh();
                } else {
                    toastr.error(null, "项目标题修改失败");
                }
            }.bind(this)
        ).error(function () {
            toastr.error(null, "项目标题修改失败");
        });
    },
    focus: function (event) {
        var input = event.target;
        //input.style.outlineStyle = "double";
        input.style.outlineColor = "#c5c5c5";
    },
    onblur: function (event) {
        var input = event.target;
        input.style.outline = "none";
        this.componentWillMount();
    },
    editProjectTitle: function () {
        this.setState({
            projectTitle: <div  tabIndex="0" onBlur={this.onblur}>
                <i className="fa fa-check-circle" title="确定"
                   style={{float:"right",marginTop:"2px",marginRight:"10px",fontSize:"19px",cursor:"pointer"}}
                   onClick={this.confirmEdit}/>
                <div>
                    <h4 style={{fontSize: "16px", marginBottom: "20px"}}>标&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;题：
                        <input id="project-edit-title" type="text"
                               onFocus={this.focus}
                               style={{border: "1px solid rgb(242, 242, 242)",width:"115px"}}
                               defaultValue={this.state.current_project.title}/>
                    </h4>
                </div>
            </div>
        });
    },
    render() {
        var project_description = "";
        if (typeof (this.state.current_project.description ) != "undefined") {
            project_description = this.state.current_project.description.length > 0 ? this.state.current_project.description : "no description";
        }
        var depen_info;
        var sync_btn_style = {
            width: "70px",
            height: "35px",
            cursor: "pointer",
            fontSize: "13px",
            backgroundColor: "#394146",
            float: "right",
            textAlign: "center"
        };
        if (this.state.dep_item.length > 0) {
            depen_info = <div className="dep_detail">
                {this.state.dependency_info}
            </div>
            sync_btn_style.display = "block";
        } else {
            sync_btn_style.display = "none";
            depen_info =
                <div style={{textAlign:"center"}}>
                    <div style={{color:"#969696",marginTop:"70px",fontSize:"14px",fontFamily:'Microsoft YaHei'}}>
                        <i className="fa fa-exclamation-circle"
                           style={{fontSize:"48px",cursor:"pointer"}}/>
                        <br/>
                        该项目没有依赖项！
                    </div>
                </div>
        }
        return (
            <div style={{height:"100%"}}>
                <div className="content_pageLeft" style={{paddingLeft: "30px"}}>
                    <span className="info_title">项目基本信息</span>
                    <h4 style={{fontSize: "16px", marginBottom: "20px",marginTop:"30px"}}>
                        命名空间：{this.state.current_project.namespace}
                    </h4>
                    <h4 style={{fontSize: "16px", marginBottom: "20px"}}>
                        名&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;称：{this.state.current_project.name}
                    </h4>
                    {this.state.projectTitle}

                    <h4 style={{fontSize: "16px", marginBottom: "20px"}}>项目简介：</h4>
                    <div className="project_intro">
                        {project_description}
                    </div>
                    {/*
                     <h4 style={{fontSize: "16px", marginBottom: "20px",marginTop: "50px"}}>工作空间信息</h4>
                     <div
                     style={{width:"244px",height:"50px", border:"1px dashed  #C4C4C4",textAlign:"center",paddingTop:"8px",marginBottom:"20px"}}>
                     <WorkspaceManage project={this.state.current_project}
                     style={{width : "100%", marginLeft:'auto',marginRight:'auto',marginTop:'50px'}}/>
                     </div>*/
                    }
                </div>
                <div className="content_pageRight">
                    <div style={{position:"absolute",width:"40%",height:"calc(100% - 50px)"}}>
                        <div style={{marginRight:"15%",marginLeft:"5%"}}>
                            <span className="info_title">项目依赖信息</span>
                            {/*<div onClick={this.updateTarget}
                             ref="sync_btn"
                             id="sync_btn"
                             style={sync_btn_style}>
                             <img src="/res/image/sync_b.png" style={{marginTop:"-2px",lineHeight: "35px"}}/>
                             <span style={{marginLeft:"5px",color:"white",lineHeight: "35px"}}>同步</span>
                             </div>*/}
                        </div>
                        <div style={{marginTop:"50xp",height:"100%"}}>
                            <div style={{ maxHeight:"calc(100% - 70px)", overflowY: "auto"}}>
                                <table id="dependency_table" style={{marginLeft:20,fontSize:16,width:"80%" }}>
                                    <tbody>
                                    {this.state.dep_item}
                                    </tbody>
                                </table>
                            </div>
                            <div onClick={this.handleOPen}
                                 style={{ textAlign:"center",cursor:"pointer",width: "110px",height: "35px",fontSize:"14px",backgroundColor:"#384045",float:"left",marginTop:"15px",marginLeft:"20px"}}>
                                <img src="/res/image/add.png" style={{marginTop:"-1px",lineHeight: "35px"}}/>
                                <span style={{marginLeft:"5px",color:"white",lineHeight: "35px"}}>添加依赖</span>
                            </div>
                        </div>
                    </div>
                    {depen_info}

                    <OrderList ref="order_list_nav" listData={order_list}
                               callback={this.refresh}
                               current_project={this.props.current_project} title="已订阅产品"/>
                </div>
            </div>
        );
    }
});

export default ProjectInfoTab;
